<template>
	<Pages :current="1" :tab="false" class="s-page">
		<view class="page-header">
			<text class="header-title" @click="onJump">图片</text>
			<pagination :total="pageData.total" @change="onPage"></pagination>
			<CustomButton text="上传图片" backgroundColor="#409eff" @click="showMediaPicker" />
		</view>


		<!-- 自定义弹窗 -->
		<media-picker ref="mediaPicker" @select="handleFileSelect" />

		<scroll-view class="tags-list" @refresherrefresh="handleRefresh" refresher-enabled :refresher-threshold="150"
			:refresher-triggered="refreshing">

			<view v-if="resources.length === 0" class="empty-state">
				<text class="empty-text">暂无图片</text>
			</view>

			<view v-else class="tags-content">
				<view v-for="resource in resources" :key="resource.id" class="tag-item"
					@longpress.stop="enterBatchMode">
					<!-- 添加选择框 -->
					<view v-if="batchMode" class="checkbox-wrapper">
						<view class="checkbox" :class="{ selected: selectedIds.has(resource.id) }"
							@click="toggleSelect(resource.id)" />
					</view>

					<view class="tag-image">
						<image :src="resource.thumbnail || resource.path" mode="aspectFill"
							@click.stop="handlePreview(resource.path)" />
					</view>

					<view class="tag-actions">
						<CustomButton text="编辑" @click="handleEditResource(resource)" backgroundColor="#67c23a" />
						<CustomButton text="删除" @click="handleDeleteResource(resource)" backgroundColor="#f56c6c" />
					</view>
				</view>
			</view>
		</scroll-view>
		<MakePopup :visible="isImgModalVisible" ref="imgModal" @confirm="handleImgSave"
			@close="isImgModalVisible = false" />

		<!-- 底部批量操作菜单 -->
		<view v-if="showBatchMenu" class="batch-menu">
			<CustomButton text="全选" @click="toggleSelectAll(resources)" />
			<CustomButton :text="`删除 (${selectedIds.size})`" backgroundColor="#f56c6c"
				:disabled="selectedIds.size === 0" @click="handleBatchDelete" />
			<CustomButton text="取消" @click="exitBatchMode" />
		</view>
	</Pages>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import CustomButton from '@/components/CustomButton.vue';
	import Pages from '@/components/pages/index.vue';
	import MediaPicker from '@/components/MediaPicker/MediaPicker.vue';
	import pagination from '@/components/pagination.vue'
	import {
		calculateMd5
	} from "./tooler";
	import {
		h5CalculateMd5,
		h5Upload
	} from "@/components/upload/utils";
	import {
		useDatabase
	} from './hooks/useDatabase';
	import {
		useResource
	} from './hooks/useResource';
	import MakePopup from './components/MakePopup.vue';

	// const SERVER_URL = 'http://localhost:4500/uni-record/resources'; // 常量定义
	const SERVER_URL = 'https://jsz315.xyz/uni-record/resources'; // 常量定义

	import useBatchSelect from './hooks/useBatchSelect'
	import {
		H5Platform
	} from './platform/H5Platform';

	// 在原有代码基础上添加
	const {
		batchMode,
		selectedIds,
		showBatchMenu,
		enterBatchMode,
		toggleSelect,
		toggleSelectAll,
		exitBatchMode
	} = useBatchSelect()

	// 新增批量删除方法
	const handleBatchDelete = async () => {
		console.log('handleBatchDelete', selectedIds.value)
		if (selectedIds.size === 0) return

		uni.showModal({
			title: '确认删除',
			content: `确定要删除选中的 ${selectedIds.value.size} 项吗？`,
			success: async (res) => {
				if (res.confirm) {
					try {
						// 这里需要根据你的API调整删除逻辑
						await Promise.all([...selectedIds.value].map(id =>
							deleteResource(resources.value.find(r => r.id === id).md5, false)
						))
						exitBatchMode()
						fetchResources()
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						})
					} catch (error) {
						uni.showToast({
							title: '删除失败',
							icon: 'none'
						})
					}
				}
			}
		})
	}

	const isImgModalVisible = ref(false);
	const imgModal = ref(null);

	const mediaPicker = ref(null);
	// const resources = ref([]);
	const refreshing = ref(false);

	// const { resources, fetchResources, deleteResource } = useDatabase(SERVER_URL);
	const {
		fetchResources,
		deleteResource,
		fetchPageResources,
		resources,
		pageData,
		findByMd5,
		h5UploadResource,
		uploadResource
	} = useResource(SERVER_URL);
	const {
		pageList,
		reset,
		createImage,
		loadMore
	} = useDatabase();

	onMounted(() => {
		fetchResources();
	});

	function onPage(page) {
		console.log('onPage', page);
		fetchPageResources(page);
	}

	function handlePreview(url) {
		uni.previewImage({
			urls: resources.value.map(el => el.path),
			current: url
		});
	}

	function onJump() {
		uni.redirectTo({
			url: "/pages/Test/Libs"
		})
	}

	async function handleImgSave(param) {
		isImgModalVisible.value = false;
		uni.showToast({
			title: '创建中',
			icon: 'loading'
		});
		const obj = await createImage(param)
		if (obj?.length) {
			console.log('创建成功', obj);
			uni.showToast({
				title: '创建成功',
				icon: 'success'
			});
		} else {
			console.log('创建失败', obj);
			uni.showToast({
				title: '创建失败',
				icon: 'none'
			});
		}
	}

	async function handleH5FileSelect(files) {
		for (const file of files) {
			const md5 = await h5CalculateMd5(file.file);
			console.log('md5', md5);
			const existingResource = await findByMd5(md5);
			if (existingResource) {
				uni.showToast({
					title: '文件已存在',
					icon: 'none'
				});
				handleRefresh();
				continue;
			}
			h5UploadResource(file.file, {
				md5
			});
		}

	}
	async function handleFileSelect(files) {
		const p = uni.getSystemInfoSync().platform;
		console.log("platform", p, uni.getSystemInfoSync().uniPlatform)
		
		if(p == "web"){
			handleH5FileSelect(files);
			return;
		}

		console.log("files", files)
		for (const file of files) {
			console.log("f", file)
			try {
				const md5 = await calculateMd5(file);
				const existingResource = await findByMd5(md5);
				if (existingResource) {
					uni.showToast({
						title: '文件已存在',
						icon: 'none'
					});
					handleRefresh();
					continue;
				}
				uploadResource(file.path, md5);
			} catch (error) {
				console.error('MD5计算失败:', error);
				uni.showToast({
					title: 'MD5计算失败',
					icon: 'none'
				});
			}
		}
	}

	function showMediaPicker() {
		mediaPicker.value.open();
	}

	function handleEditResource(resource) {
		console.log("Editing resource:", resource);
		// 编辑逻辑
		isImgModalVisible.value = true;
		imgModal.value.open(resource.path);
	}

	function handleDeleteResource(resource) {
		uni.showModal({
			title: '确认删除',
			content: '确定要删除该资源吗？',
			success: async (res) => {
				if (res.confirm) {
					try {
						await deleteResource(resource.md5);
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
					} catch (error) {
						uni.showToast({
							title: '删除失败',
							icon: 'none'
						});
					}
				}
			}
		});
	}

	async function handleRefresh() {
		refreshing.value = true;
		await fetchResources(true);
		refreshing.value = false;
	}
</script>


<style lang="scss" scoped>
	:deep(.uni-scroll-view-refresher) {
		background: none !important;
		margin-bottom: 20rpx;
	}

	.s-page {
		height: 100vh;
		// left: 0;
		// top: 0;
		// width: 100vw;
		// box-sizing: border-box;
		display: flex;
		// padding: 20rpx;
		// padding-top: 80px !important;
		flex-direction: column;
		// .tags-list{
		//   flex: 1;
		//   height: 0;
		// }
	}

	.page-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		position: sticky;
		background: #f6f6f6;
		top: 0;
		z-index: 1;

		.header-title {
			font-size: 36rpx;
			font-weight: bold;
		}
	}

	.tags-list {

		.loading-state,
		.empty-state {
			// background: #fff;
			border-radius: 12rpx;
			padding: 48rpx;
			text-align: center;
			color: #909399;
			font-size: 28rpx;
		}

		.loading-state {
			background: transparent;
			margin: 20rpx 0;
		}

		.loading-more,
		.no-more {
			text-align: center;
			padding: 20rpx;
			color: #909399;
			font-size: 24rpx;
		}
	}

	.tags-content {
		display: grid;
		grid-template-columns: repeat(3, 1fr); // 一行3个
		gap: 16rpx;

		.tag-item {
			position: relative;
			// width: calc(50% - 8px); // 计算宽度以适应一行两列
			box-shadow: 0 4px 8px rgba(0, 0, 0, .1);
			border-radius: 8px;
			overflow: hidden;
			background-color: #fff;

			.tag-image {
				width: 100%;
				height: 200px; // 设置固定高度或其他合适的值

				image {
					width: 100%;
					height: 100%;
					object-fit: cover;
				}
			}

			.tag-actions {
				padding: 4px 0;
				display: flex;
				justify-content: space-around;
				background-color: #f9f9f9;

				button {
					flex: 1;
					// margin: 0 4px;
					padding: 2px;
					border: none;
					border-radius: 4px;
					color: #fff;
					font-size: 14px;
					cursor: pointer;
					transform: scale(0.8);
				}
			}
		}
	}

	/* 新增样式 */
	.checkbox-wrapper {
		position: absolute;
		right: 8px;
		top: 8px;
		z-index: 2;
	}

	.checkbox {
		width: 30px;
		height: 30px;
		border: 2px solid #fff;
		border-radius: 50%;
		background: rgba(0, 0, 0, 0.5);
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
	}

	.checkbox.selected {
		background: #409eff;
		// border-color: #409eff;
		display: flex;
		justify-content: center;
		align-items: center;

		&::after {
			content: '';
			display: block;
			width: 20px;
			height: 20px;
			border-radius: 50%;
			background: url("/static/icons/right.png") no-repeat center;
			background-size: contain;
		}
	}

	.batch-menu {
		z-index: 4;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background: rgba(255, 255, 255, 0.95);
		padding: 16rpx;
		display: flex;
		justify-content: space-around;
		box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.1);
	}
</style>